package com.liuxing.doctor.controller;

import com.liuxing.doctor.common.Object.ReturnObject;
import com.liuxing.doctor.common.util.DateUtils;
import com.liuxing.doctor.dto.PatientDto;
import com.liuxing.doctor.entity.Doctor;
import com.liuxing.doctor.entity.MedicalRecord;
import com.liuxing.doctor.entity.Patient;
import com.liuxing.doctor.service.MedicalRecordService;
import com.liuxing.doctor.service.PatientService;
import com.liuxing.doctor.service.PrescriptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @athuer 行柳
 */
@Slf4j
@Controller
@RequestMapping("/main")
public class MainController {
    private int i=0;
    @Resource
    private PatientService patientService;
    @Resource
    private MedicalRecordService medicalRecordService;
    @Resource
    private PrescriptionService prescriptionService;
    /**
     * 跳转主页面
     * @return
     */
    @RequestMapping("/index")
    public String index(Model model, HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        model.addAttribute("doctor",doctor);
        return "main/index";
    }

    /**
     * 显示当前医生已经诊断病人列表
     * @return
     */
    @RequestMapping(value = "/diagnosis_done_patient_list")
    @ResponseBody
    public Object patient_list_done(HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        List<Patient> patients=patientService.queryAllPatientWithMedicalRecordIdNotNull(doctor.getDoctorId());
        Map<String,Object> resMap=new HashMap<>();
        resMap.put("patients",patients);
        return resMap;
    }
    /**
     * 显示当前医生没有诊断病人列表
     * @return
     */
    @RequestMapping(value = "/no_diagnosis_done_patient_list")
    @ResponseBody
    public Object no_patient_list_done(HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        List<Patient> patients=patientService.queryAllPatientWithMedicalRecordIdNull();
        Map<String,Object> resMap=new HashMap<>();
        resMap.put("patients",patients);
        return resMap;
    }

    /**
     * 回显病人最新病历信息
     * @param patient_id
     * @return
     */
    @RequestMapping("/patient_medical_record")
    @ResponseBody
    public Object patient_medical_record(String patient_id){
        Patient patient=patientService.queryById(patient_id);
        PatientDto patientDto=new PatientDto();
        patientDto.setPatient(patient);
        MedicalRecord medicalRecord=medicalRecordService.queryById(patient.getMedicalRecordId());

        if(medicalRecord!=null){
            patientDto.setMedicalRecordId(String.valueOf(medicalRecord.getMedicalRecordId()));
            patientDto.setSymptom(medicalRecord.getSymptom());
            patientDto.setDiagnosis(medicalRecord.getDiagnosis());
            patientDto.setTreatmentOptions(medicalRecord.getTreatmentOptions());
            return patientDto;
        }
        return patientDto;
    }

    /**
     * 根据search_name查询病人
     * @param search_name
     * @return
     */
    @RequestMapping(value = "/queryBySearchName")
    @ResponseBody
    public Object queryBySearchName(String search_name,HttpServletRequest request,boolean whether_diagnosis_flag){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        Map<String,Object> resMap=new HashMap<>();
        if(whether_diagnosis_flag){
            List<Patient> patients=patientService.queryPatientBySearchNameWithDoneDiagnosis(search_name, doctor.getDoctorId());
            resMap.put("patients",patients);
        }else{
            List<Patient> patients=patientService.queryPatientBySearchNameWithNoDoneDiagnosis(search_name);
            resMap.put("patients",patients);
        }
        return resMap;
    }

    /**
     * 保存或更新病人病历
     * @param patient_id
     * @param symptom
     * @param diagnosis
     * @param treat
     * @return
     */
    @RequestMapping("/saveAndUpdateMedicalRecord")
    @ResponseBody
    @Transactional
    public Object saveAndUpdateMedicalRecord(
            String patient_id,String symptom,String diagnosis,String treat,String medical_record_id
    ) {
        String editDateTime= DateUtils.formateDateTime(new Date());
        ReturnObject returnObject=new ReturnObject();
        Map<String,Object> map=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        if(patient.getMedicalRecordId()==0){
            returnObject.setCode("0");
            returnObject.setMessage("请先为该病人创建新的病历");
            return returnObject;
        }
        map.put("symptom",symptom);
        map.put("diagnosis",diagnosis);
        map.put("treat",treat);
        map.put("patient_id",patient_id);
        map.put("editDateTime",editDateTime);
        map.put("medicalRecordId",medical_record_id);
        int rescode=medicalRecordService.updateMedicalRecord(map);
        if(rescode==1){
            returnObject.setCode("1");
            returnObject.setMessage("保存成功");
        }else{
            returnObject.setMessage("网络连接错误，响应超时，请稍后再试");
            returnObject.setCode("0");
        }
        return returnObject;
    }

    /**
     * 新建病人病历
     * @param symptom
     * @param diagnosis
     * @param treat
     * @param patient_id
     * @param request
     * @return
     */
    @Transactional
    @RequestMapping("/createMedicalRecord")
    @ResponseBody
    public Object createMedicalRecord(String symptom,String diagnosis,String treat,String patient_id,HttpServletRequest request){
        //创建新的病历
        String createDateTime= DateUtils.formateDateTime(new Date());
        String editDateTime= DateUtils.formateDateTime(new Date());
        Map<String,Object> map=new HashMap<>();
        map.put("symptom",symptom);
        map.put("diagnosis",diagnosis);
        map.put("treat",treat);
        map.put("createDateTime",createDateTime);
        map.put("patient_id",patient_id);
        map.put("editDateTime",editDateTime);
        int resCode_create=medicalRecordService.createMedicalRecord(map);
        //更新病人的信息
        List<MedicalRecord> medicalRecords=medicalRecordService.queryByPatientId(patient_id);
        //获取最新创建的病历
        MedicalRecord medicalRecord=medicalRecords.stream().sorted((x,y)->
            DateUtils.formateDateTime(y.getCreateTime()).compareTo(DateUtils.formateDateTime(x.getCreateTime()))
        ).collect(Collectors.toList()).get(0);
        Map<String,Object> map1=new HashMap<>();
        String medicalRecordId= String.valueOf(medicalRecord.getMedicalRecordId());
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        map1.put("patientNumber",doctor.getDoctorId());
        map1.put("medicalRecordId",medicalRecordId);
        map1.put("patientId",patient_id);
        int resCode_update=patientService.updatePatient(map1);
        Map<String,Object> resMap=new HashMap<>();
        if(resCode_create==1&&resCode_update==1){
            //判断病人是否有处方，给病人新建一个新的空的处方
            if(prescriptionService.queryPrescriptionsByPatientId(patient_id).size()==0){
                Map<String,Object> createNullPrescription=new HashMap<>();
                createNullPrescription.put("createDateTime",createDateTime);
                createNullPrescription.put("patient_id",patient_id);
                createNullPrescription.put("doctor_id",doctor.getDoctorId());
                prescriptionService.createNullPrescriptionByPatientId(createNullPrescription);
            }
            resMap.put("symptom",medicalRecord.getSymptom());
            resMap.put("diagnosis",medicalRecord.getDiagnosis());
            resMap.put("treat",medicalRecord.getTreatmentOptions());
            resMap.put("medicalRecordId",medicalRecord.getMedicalRecordId());
            return resMap;
        }
        resMap.put("code","0");
        return resMap;
    }

    @RequestMapping("/delete")
    @ResponseBody
    @Transactional
    public Object delete(String patient_id){
        log.info("---------------执行----------------");
        ReturnObject returnObject=new ReturnObject();
        int resCode1=patientService.deletePatient(patient_id);
        int resCode2=medicalRecordService.deleteMedicalRecord(patient_id);
        int resCode3=prescriptionService.deletePrescriptionsByPatientId(patient_id);
        if(resCode1==1&&resCode2>=0&&resCode3>=0){
            returnObject.setCode("1");
            returnObject.setMessage("删除成功");
        }else{
            returnObject.setMessage("服务器连接失败,请检查网络连接");
        }
        return returnObject;
    }
    @RequestMapping("/print")
    @ResponseBody
    public Object print(String patient_id,HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        Map<String,Object> resMap=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        if(patient.getMedicalRecordId()==0){
            resMap.put("code","0");
            resMap.put("msg","请先为该病人创建新的病历");
            return resMap;
        }
        MedicalRecord medicalRecord=medicalRecordService.queryById(patient.getMedicalRecordId());
        resMap.put("symptom",medicalRecord.getSymptom());
        resMap.put("diagnosis",medicalRecord.getDiagnosis());
        resMap.put("treat",medicalRecord.getTreatmentOptions());
        resMap.put("date",DateUtils.formateDate(medicalRecord.getCreateTime()));
        resMap.put("doctorName",doctor.getDoctorName());
        resMap.put("department",doctor.getDoctorDepartment());
        resMap.put("patientName",patient.getPatientName());
        resMap.put("patientSexy",patient.getPatientSex());
        resMap.put("patientAge",patient.getPatientAge());
        return resMap;
    }
}
